package org.example.callback;

public class Client {

    public static void main(String[] args) {
        Callback callback = new Callback() {
            @Override
            public void onCompleted() {
                System.out.println("Task completed!");
            }
        };

//        Task task = new Client().new Task(callback);
//        task.execute();

        //Java 8或更高版本，可以利用Lambda表达式来简化回调的实现
        Task task = new Client().new Task(() -> System.out.println("Task completed!"));
        task.execute();
    }


    interface Callback {
        void onCompleted();
    }

    class Task {
        private Callback callback;

        public Task(Callback callback) {
            this.callback = callback;
        }

        public void execute() {
            // 执行一些操作
            System.out.println("Task is executing...");
            // 操作完成后调用回调
            if (callback != null) {
                System.out.println("开始回调...");
                callback.onCompleted();
            }
        }
    }

}
